package com.michaelbulava.TFS.tasks.connect;

import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.michaelbulava.TFS.ui.config.ClientConnectionAdvisor;
import com.microsoft.tfs.core.TFSConnection;
import com.microsoft.tfs.core.TFSTeamProjectCollection;
import com.microsoft.tfs.core.httpclient.Credentials;

import java.net.URI;

/**
 * Created by MichaelA on 8/4/2015.
 */
public abstract class ConnectToCollectionTask extends ConnectTask {
    private boolean performAuthentication = false;

    public ConnectToCollectionTask(Project project, URI serverURI) {
        this(project, serverURI, null);
    }

    public ConnectToCollectionTask(Project project, URI serverURI, Credentials credentials) {
        super(project, serverURI, credentials);
    }

    public void authenticateConnection(boolean value){
        performAuthentication = value;
    }


    @Override
    protected ConnectCommand getConnectCommand(URI serverURI, Credentials credentials) {
        return new ConnectToProjectCollectionCommand(serverURI, credentials, performAuthentication);
    }



    public static class ConnectToProjectCollectionCommand implements ConnectCommand{
        private TFSTeamProjectCollection connection;
        private final URI serverURI;
        private final Credentials credentials;
        private boolean finished = false;
        private Throwable exception = null;
        private final boolean authenticate;

        public ConnectToProjectCollectionCommand(URI serverURI, Credentials credentials, boolean authenticate){
            this.serverURI = serverURI;
            this.credentials = credentials;
            this.authenticate = authenticate;
        }

        @Override
        public TFSConnection getConnection() {
            return connection;
        }

        @Override
        public boolean finishedOk() {
            return exception == null && finished;
        }

        @Override
        public Throwable getException() {
            return exception;
        }

        @Override
        public void execute(ProgressIndicator progress) {
            exception= null;
            connection = new TFSTeamProjectCollection(serverURI, credentials, new ClientConnectionAdvisor());

            if (authenticate){
                try {
                    connection.authenticate();
                    finished = true;
                } catch (Throwable e) {
                    if (connection != null) {
                        connection.close();
                    }
                    //throw e;
                    exception = e;
                }
            } else {
                finished = true;
            }

        }
    }
}
